<template>
  <div class="card">
    <div class="flex justify-between items-center">
      <h2 class="text-lg font-bold">消费市场（限额以上）</h2>
      <a-button type="primary" @click="createMarketConsumptionReport"
        >生成报告
        <a-modal
          v-model:visible="createMarketConsumptionReportModal"
          title="消费市场（限额以上）报告"
        >
          <p>暂无数据...</p>
        </a-modal>
      </a-button>
    </div>

    <div class="p-4 h-64 relative">
      <!-- 显示各行业全年综合 -->
      <div>
        <span v-for="(dataset, index) in formattedChartData.datasets" :key="index" class="mr-3">
          {{ dataset.label }}：<span class="font-bold">{{ getTotal(dataset.data) }}</span>
        </span>
      </div>
      <LineChart
        :data="formattedChartData"
        :options="chartOptions"
        class="w-full h-full chart-container"
      />
      <!-- 数据卡片悬浮层 -->
      <div
        v-if="hoverData"
        class="absolute bg-white rounded-lg shadow-lg p-3 z-10 transition-opacity duration-200"
        :style="{ left: hoverData.x + 'px', top: hoverData.y + 'px' }"
      >
        <div class="font-semibold text-sm text-gray-800">{{ hoverData.label }}</div>
        <div class="flex items-center mt-1">
          <span
            class="inline-block w-2 h-2 rounded-full mr-1"
            :style="{ backgroundColor: hoverData.color }"
          ></span>
          <span class="text-xs text-gray-600"
            >{{ hoverData.datasetLabel }}: {{ hoverData.value }}</span
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {
  Chart as ChartJS,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'

// 注册Chart.js组件
ChartJS.register(LinearScale, PointElement, LineElement, Title, Tooltip, Legend)
const createMarketConsumptionReportModal = ref(false)

// 原始数据
const rawChartData = {
  labels: ['2020年', '2021年', '2022年', '2023年', '2024年'],
  datasets: [
    {
      label: '批发业',
      data: [120, 140, 160, 145, 170],
      borderColor: '#165DFF',
      backgroundColor: 'rgba(22, 93, 255, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#165DFF',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '零售业',
      data: [80, 95, 105, 120, 110],
      borderColor: '#FF7D00',
      backgroundColor: 'rgba(255, 125, 0, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#FF7D00',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '住宿业',
      data: [30, 35, 40, 45, 50],
      borderColor: '#00B42A',
      backgroundColor: 'rgba(0, 180, 42, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#00B42A',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '餐饮业',
      data: [40, 45, 55, 60, 70],
      borderColor: '#F53F3F',
      backgroundColor: 'rgba(245, 63, 63, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#F53F3F',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
  ],
}

const hoverData = ref(null)

// 使用计算属性格式化图表数据
const formattedChartData = computed(() => {
  return {
    ...rawChartData,
    datasets: rawChartData.datasets.map((dataset) => ({
      ...dataset,
      // 可以在此处添加数据格式化逻辑
    })),
  }
})

const chartOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
      labels: {
        usePointStyle: true,
        boxWidth: 6,
        color: '#666',
        font: {
          size: 11,
        },
        padding: 15,
      },
    },
    padding: {
      bottom: 20, // 底部内边距，可根据需要调整
    },
    tooltip: {
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      titleColor: '#333',
      bodyColor: '#666',
      borderColor: 'rgba(0, 0, 0, 0.05)',
      borderWidth: 1,
      padding: 10,
      boxPadding: 5,
      usePointStyle: true,
      callbacks: {
        label: function (context) {
          return ` ${context.dataset.label}: ${context.raw}`
        },
      },
      // 自定义tooltip位置
      external: function (context) {
        const tooltip = context.tooltip
        if (tooltip.opacity === 0) {
          hoverData.value = null
          return
        }

        const position = context.chart.canvas.getBoundingClientRect()
        hoverData.value = {
          x: position.left + tooltip.caretX,
          y: position.top + tooltip.caretY,
          label: tooltip.title[0],
          value: tooltip.dataPoints[0].raw,
          datasetLabel: tooltip.dataPoints[0].dataset.label,
          color: tooltip.dataPoints[0].dataset.borderColor,
        }
      },
    },
  },
  scales: {
    x: {
      grid: {
        display: false,
      },
      ticks: {
        color: '#999',
        font: {
          size: 11,
        },
      },
    },
    y: {
      beginAtZero: true,
      grid: {
        color: 'rgba(0, 0, 0, 0.05)',
        drawBorder: false, // 不绘制边框
      },
      ticks: {
        color: '#999',
        font: {
          size: 11,
        },
        padding: 15, // 增加刻度与图表边缘的间距
        callback: function (value) {
          return value + '亿' // 可选：添加单位，使刻度更清晰
        },
      },
    },
  },
  interaction: {
    mode: 'index',
    intersect: false,
  },
  animation: {
    duration: 1000,
    easing: 'easeOutQuart',
  },
})

// 计算数组总和的方法
const getTotal = (arr) => {
  return arr.reduce((acc, cur) => acc + cur, 0)
}

// 社会消费品生成报告
const createMarketConsumptionReport = () => {
  createMarketConsumptionReportModal.value = true
}
</script>

<style scoped>
/* 可以在这里添加必要的样式优化 */
canvas {
  width: 100% !important;
  height: 250px !important;
}
.chart-container {
  padding-bottom: 20px; /* 增加图表底部内边距 */
}
.card {
  overflow: hidden;
}
</style>
